<template>
      <a-card :bordered="false">
        <search ref="search"  :config="searchConfig" @search="search" @getHeight="getHeight"/>
        <!-- 操作按钮区域 -->

        <div class="table-operator">
          <a-button @click="handleAdd" v-has="'cust:add'" type="primary">新增</a-button>
<!--                    <a-button @click="handleEdit(model1)" type="primary">角色编辑</a-button>-->
<!--                    <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--                      <a-button type="primary" icon="import">导入</a-button>-->
<!--                    </a-upload>-->
          <a-button type='primary' v-has="'dealer:getOut'" icon='download' @click="downExportXls('customer_service')">导出</a-button>
        </div>

<!--        <div class="ant-alert ant-alert-info" style="margin-bottom: 8px;">-->
<!--          <i class="anticon anticon-info-circle ant-alert-icon">-->
<!--          </i> 已选择 <a><b>{{ selectedRowKeys1.length }}</b></a>项-->
<!--          <a style="margin-left: 24px" @click="onClearSelected1">清空</a>-->
<!--        </div>-->

        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :scroll="{x:1500,y:pageHeight-seachHeight-220}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :customRow="onClickRow"
            :rowSelection="{selectedRowKeys: selectedRowKeys1, onChange: onSelectChange1, type:'checkbox'}"
            @change="handleTableChange">
            <template slot="name" slot-scope="t,r">
              <a-tooltip :autoAdjustOverflow="true">
                <template slot="title">
                t
                </template>
              </a-tooltip>
            </template>
            <template slot="avatar" slot-scope="text, record, index">
              <div class="anty-img-wrap">
                <a-avatar shape="square" :src="record.avatar" icon="user" />
              </div>
            </template>
            <div slot="isActiveStatus" slot-scope="text,recode">
              {{ text|isActiveStatus }}
            </div>
            <div slot="filterCustType" slot-scope="text,recode">
              {{ text|filterCustType }}
            </div>
            <span slot="action" slot-scope="text, record">
<!--              <a @click="handleOpen(record)">用户</a>-->
<!--              <a-divider type="vertical" />-->
              <a @click="handleEdit(record)" v-has="'dealer:edit'">编辑</a>
<!--              <a-divider type="vertical" />-->
<!--              <a @click="handleDetail(record)">查看</a>-->
            </span>
          </a-table>
        </div>
        <!-- 右侧的角色权限配置 -->
        <dealer-modal ref="modalForm" @ok="modalFormOk"></dealer-modal>
        <userContact ref="usercon"></userContact>
      </a-card>
</template>
<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import { deleteAction, postAction, getAction } from '@/api/manage'
import userContact from './modules/UserContact'
import UserModal from '@page-modules/UserModal'
import { filterObj } from '@/utils/util'
import UserRoleModal from '@page-modules/UserRoleModal'
import dealerModal from './modules/DealerModal'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import moment from 'moment'

export default {
  name: 'DealerUserList',
  mixins: [PageListMixin],
  components: {
    UserRoleModal,
    userContact,
    UserModal,
    moment,
    dealerModal,
    JTreeSelect,
  },
  data() {
    return {
      searchConfig:[
        {
          type:'input',
          name:'erpCode',
          placeholder:'请输入经销商编号',
        },{
          type:'input',
          name:'customerName',
          placeholder:'请输入经销商名称',
        },{
          type:'j-select',
          name:'extChar2',
          dictCode:"cust_Level",
          placeholder:'请选择经销商层级',
        },{
          type:'tree-select',
          name:'orgCode',
          dataType:'org',
          placeholder:'请选择经销商组织',
        },
        {
          type:'j-select',
          name:'customerLevel',
          dictCode:"cust_level",
          placeholder:'请选择经销商等级',
        }
      ],
      permflag: 'cust_page_impl',
      model1: {},
      model2: {},
      currentRoleId: '',
      queryParam1: {},
      queryParam2: {},
      dataSource1: [],
      dataSource2: [],
      ipagination1: {
        current: 1,
        size: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },

      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter1: {
        column: 'createTime',
        order: 'desc'
      },
      isorter2: {
        column: 'createTime',
        order: 'desc'
      },
      filters1: {},
      filters2: {},
      loading1: false,
      loading2: false,
      selectedRowKeys1: [],
      selectedRowKeys2: [],
      selectionRows1: [],
      selectionRows2: [],
      test: {},
      columns: [
          {
            title: '经销商编号',
            align: 'center',
            width:100,
            dataIndex: 'erpCode',
            fixed:'left',
            customRender: (value, row, index) => {
              let vm = this
              let child = vm.$createElement('a', {
                domProps: {
                  innerHTML: value
                },
                on: {
                  click: function() {
                    vm.handleDetail(row)
                  }
                }
              })
              const obj = {
                children: child,
                attrs: {}
              }
              return obj
            }
          },
          {
            title: 'CRM经销商编号',
            align: 'center',
            width:150,
            dataIndex: 'customerCode',
            fixed:'left'
          },
          {
            title: '经销商名称',
            align: 'center',
            dataIndex: 'customerName'
          },
          {
            title: '经销商类型',
            align: 'center',
            width: 100,
            dataIndex: 'customerTypeStr'
          },
          {
            title: '经销商层级',
            align: 'center',
            width: 100,
            dataIndex: 'extCharStr2'
          },
          {
            title: '所属组织',
            align: 'center',
            width: 100,
            dataIndex: 'orgName'
          },
          {
            title: '联系电话',
            align: 'center',
            width: 150,
            dataIndex: 'linkmanPhone'
          },
          // {
          //   title: '关联职位',
          //   align: 'center',
          //   dataIndex: 'name',
          //   width: 150,
          //   ellipsis: true,
            // customRender: (r, t) =>{
            //   let vm =new Vue
            //   console.log(vm)
            // return  vm.$createElement('div',{
            //   domProps: {
            //     innerHTML: r
            //   },
            //   style:{
            //     whiteSpace:'nowrap',
            //     color: 'red',
            //     textOverflow: 'ellipsis',
            //     overflow:'hidden'
            //
            //   }
            // })
            //
            // }
          // },
          {
            title: '合作日期',
            align: 'center',
            width: 150,
            dataIndex: 'cooperateDate'
          },
         {
            title: '经销商等级',
            align: 'center',
           width: 150,
            dataIndex: 'customerLevelStr'
          },
          {
            title: '状态',
            align: 'center',
            dataIndex: 'enableStatus',
            fixed:'right',
            width:100,
            scopedSlots: { customRender: 'isActiveStatus' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed:'right',
            width: 80,
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'
            }
          }
        ],
      queryParam: {

      },
      // 高级查询参数
      superQueryParams2: '',
      // 高级查询拼接条件
      superQueryMatchType2: 'and',
      url: {
        list: window._CONFIG['domianURL'] + '/customerController/getPageList',
        delete: window._CONFIG['domianURL'] + '/customerController/deleteByid',
        detail: window._CONFIG['domianURL'] + '/customerController/getCnCustomerByIdOrCustCode',
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    leftColMd() {
      return this.selectedRowKeys1.length === 0 ? 24 : 12
    },
    rightColMd() {
      return this.selectedRowKeys1.length === 0 ? 0 : 12
    }
  },
  methods: {
    handleEdit(record) {
       getAction(this.url.detail, {id: record.id}).then(res=>{
         if (res && res.result) {
           record = res.result
           this.$refs.modalForm.edit(record);
           this.$refs.modalForm.title = "编辑";
           this.$refs.modalForm.disableSubmit = false;
         }else{
           this.$message.error(res.message)
         }
       })
    },
    onClickRow(record) {
      return {
        on: {
          click: () => {
            let keys = this.selectedRowKeys1
            if (keys.indexOf(record.id) == -1) {
              keys.push(record.id)
              this.selectionRows1.push(record)
            } else {
              keys.remove(record.id)
              this.selectionRows1.remove(record)
            }
            this.selectedRowKeys1 = keys

          }
        }
      }
    },
    onClearSelected1() {
      this.selectedRowKeys1 = []
      this.selectionRows1 = []
    },
    onSelectChange1(selectedRowKeys, selectionRows) {

      this.selectedRowKeys1 = selectedRowKeys
      this.selectionRows1 = selectionRows
    },
    onClearSelected() {
    },

    getQueryParams2() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams2) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams2)
        sqp['superQueryMatchType'] = this.superQueryMatchType2
      }
      var param = Object.assign(sqp, this.queryParam2, this.isorter2, this.filters2)
      param.field = this.getQueryField2()
      param.current = this.ipagination2.current
      param.size = this.ipagination2.pageSize
      return filterObj(param)
    },

    handleEdit2: function(record) {
      this.$refs.modalForm2.title = '编辑'
      this.$refs.modalForm2.roleDisabled = true
      this.$refs.modalForm2.edit(record)
    },
    handleAdd2: function() {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.modalForm2.roleDisabled = true
        this.$refs.modalForm2.selectedRole = [this.currentRoleId]

        this.$refs.modalForm2.add()

        this.$refs.modalForm2.title = '新增'
      }
    },

    loadData2(arg) {
      if (!this.url.list2) {
        this.$message.error('请设置url.list2属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination2.current = 1
      }
      if (this.currentRoleId === '') return
      let params = this.getQueryParams2()//查询条件
      params.custCode = this.currentRoleId
      this.loading2 = true
      var that = this
      postAction(this.url.list2, params).then((res) => {
        if (res.success) {
          that.dataSource2 = res.result.records
          that.ipagination2.total = res.result.total

        }
        that.loading2 = false
      })

    },
    handleDelete1: function(id) {
      this.handleDelete(id)
      this.dataSource2 = []
      this.currentRoleId = ''
    },

    batchDel2: function() {

      if (!this.url.deleteBatch2) {
        this.$message.error('请设置url.deleteBatch2属性!')
        return
      }
      if (this.selectedRowKeys2.length <= 0) {
        this.$message.warning('请选择一条记录！')

      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys2.length; a++) {
          ids += this.selectedRowKeys2[a] + ','
        }
        var that = this
        console.log(this.currentDeptId)
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function() {
            deleteAction(that.url.deleteBatch2, { roleId: that.currentRoleId, userIds: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData2()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },

    handleAddUserRole() {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.selectUserModal.isfilterRole = 1
        this.$refs.selectUserModal.visible = true
        this.$refs.selectUserModal.custCode = this.currentRoleId
      }
    },
    handleOpen(record) {

      this.selectedRowKeys1 = [record.id]
      this.model1 = Object.assign({}, record)

      this.currentRoleId = record.custCode

      this.$refs.usercon.showDrawer(record)

      // this.onClearSelected2()
      // this.loadData2()
    },
    /*handleEdit: function(record) {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
      }
    },*/
    searchQuery2() {
      this.loadData2(1)
    },
    searchReset2() {
      this.queryParam2 = {}
      this.loadData2(1)
    },

    hideUserList() {
      this.selectedRowKeys1 = []
    },
    handlePerssion(roleId) {
      this.$refs.modalUserRole.show(roleId)
    }
  }
}
</script>
<style scoped>
/** Button按钮间距 */
.ant-btn {
  /*margin-left: 8px*/
  margin-bottom: 8px;
}


</style>
